import hashlib

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from blog.models import User


def login_page(request):
    return render(request, 'login.html')


def reg_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')

    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        md=hashlib.md5()
        md.update(password.encode())
        password=md.hexdigest()
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')
        try:
            user=User.objects.create(username=username,password=password)
        except Exception as e:
            print('---create user error %s'%(e))
            return HttpResponse('用户名已注册')

        # User.objects.create(username=username, password=password)

        request.session['username'] = username
        request.session['uid'] = user.id
        request.session.set_expiry(259200)

    return HttpResponse('注册成功')
